package com.zlq.cn.config;

import lombok.SneakyThrows;
import net.sourceforge.tess4j.Tesseract;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;

//@Configuration
public class Tess4jConfig {

    @Value("${tess4j.datapath}")
    public String dataPath;

    @Bean
    public Tesseract tesseract() {
        Tesseract tesseract = new Tesseract();
        // 设置训练数据文件夹路径
        tesseract.setDatapath(dataPath);
        // 设置为中文简体 eng+
        tesseract.setLanguage("chi_sim");
        return tesseract;
    }

    @SneakyThrows
    public static void main(String[] args) {
        Tess4jConfig tess4jConfig = new Tess4jConfig();
        tess4jConfig.dataPath = "D:/develop/Java/project/zlq/file/tess4j";
        Tesseract tesseract = tess4jConfig.tesseract();
        BufferedImage bufferedImage = ImageIO.read(new File("C:\\Users\\Administrator\\Desktop\\微信图片_20240708132856.jpg"));
        // 二值化
        bufferedImage = toBlackAndWhite(bufferedImage); // threshold value
//        BufferedImage blackAndWhiteImage = new BufferedImage(bufferedImage.getWidth(), bufferedImage.getHeight(), BufferedImage.TYPE_BYTE_BINARY);
//        Graphics2D graphics = blackAndWhiteImage.createGraphics();
//        graphics.drawImage(bufferedImage, 0, 0, null);
//        graphics.dispose();
//        ImageIO.write(bufferedImage, "jpg", new File("C:\\Users\\Administrator\\Desktop\\微信图片_20240708132856_2.jpg"));
        // 对图片进行文字识别
        String s = tesseract.doOCR(bufferedImage);
        System.out.println(s);
    }

    public static BufferedImage toBlackAndWhite(Image image) {
        BufferedImage bwImage = new BufferedImage(
                image.getWidth(null),
                image.getHeight(null),
                BufferedImage.TYPE_BYTE_GRAY);
        Graphics2D g = bwImage.createGraphics();
        g.drawImage(image, null, null);
        g.dispose();
        return bwImage;
    }
}
